package org.springblade.wechat.componet;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springblade.wechat.util.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;


/**
 * @author LK
 * @version 1.0.0
 * @Title: AccessTokenThread.java
 * @Description: TODO    通行令牌线程
 * @date 2020/4/7 15:41
 */
@Component
public class AccessTokenThread {

	private static Logger logger = LoggerFactory.getLogger(AccessTokenThread.class);

	@Autowired
	private RedisTemplate<String, String> redisTemplate;

	@Value("${wechat.appID}")
	private String APP_ID;

	@Value("${wechat.secret}")
	private String SECRET;

	private final String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

	/**
	 * 获取并保存通行令牌到redis
	 */
	@Scheduled(fixedDelay = 2 * 2700 * 1000)
	public void getAccessToken() {
		String info = HttpClientUtil.doGet(getAccess_toke_url());
		logger.info("请求获取userInfo" + info);
		JSONObject jsonObject = JSONObject.parseObject(info);
		if (jsonObject == null) {
			return;
		}
		if (jsonObject.containsKey("errcode")) {
			int errcode = jsonObject.getIntValue("errcode");
			String errmsg = jsonObject.getString("errmsg");
			if (errcode == -1) {
				logger.info("系统繁忙，此时请开发者稍候再试!" + "=====" + errmsg);
			} else if (errcode == 0) {
				logger.info("请求成功" + "=====" + errmsg);
			} else if (errcode == 40001) {
				logger.info("AppSecret错误或者AppSecret不属于这个公众号，请开发者确认AppSecret的正确性" + "=====" + errmsg);
			} else if (errcode == 40002) {
				logger.info("请确保grant_type字段值为client_credential" + "=====" + errmsg);
			} else if (errcode == 40164) {
				logger.info("调用接口的IP地址不在白名单中，请在接口IP白名单中进行设置。（小程序及小游戏调用不要求IP地址在白名单内。）" + "=====" + errmsg);
			} else if (errcode == 89503) {
				logger.info("此IP调用需要管理员确认,请联系管理员" + "=====" + errmsg);
			} else if (errcode == 89501) {
				logger.info("此IP正在等待管理员确认,请联系管理员" + "=====" + errmsg);
			} else if (errcode == 89506) {
				logger.info("系24小时内该IP被管理员拒绝调用两次，24小时内不可再使用该IP调用" + "=====" + errmsg);
			} else if (errcode == 89507) {
				logger.info("1小时内该IP被管理员拒绝调用一次，1小时内不可再使用该IP调用" + "=====" + errmsg);
			}
		} else {
			redisTemplate.boundValueOps("access_token").set(jsonObject.getString("access_token"));
			redisTemplate.boundValueOps("expires_in").set(jsonObject.getString("expires_in"));
		}
		redisTemplate.boundValueOps("access_token").get();
	}

	/**
	 * 获取通行令牌
	 *
	 * @return
	 */
	public String getAccess_toke_url() {
		System.out.println("access_toke_url======:" + url + "&appid=" + APP_ID + "&secret=" + SECRET);
		return url + "&appid=" + this.APP_ID + "&secret=" + this.SECRET;
	}
}
